<?php

namespace App\Admin\Forms\Employee;

use Encore\Admin\Widgets\Form;
use Encore\Cropper\Crop;
use Illuminate\Http\Request;
use App\Admin\Models\SequenceModel;
use App\Admin\Models\UserModel;
use App\Admin\Models\EmployeeModel;
use App\Admin\Models\PositionModel;

class Basic extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '基本信息';

    /**
     * @var bool 是否展示模式
     */
    public $isShow = false;

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {
        $data = \Request::input();
        $id   = !empty($data['employee_id']) ? (int)$data['employee_id'] : 0;
        if ($id) {
            $model = EmployeeModel::find($id);
        } else {
            $model = new EmployeeModel();
        }
        unset($data['employee_id']);

        // 图片处理
        $path = '';
        if (!empty($data['user_id'])) {
            $user = UserModel::find($data['user_id']);
            if ($user) {
                $path = $user->avatar;
            }

            // 检测user_id是否重复
            $exist = EmployeeModel::where('user_id', $data['user_id'])->whereRaw('employee_id <> ' . $id)->first();
            if ($exist) {
                admin_toastr('当前后台账号已绑定其他人员【' . $exist->name_zh . '】，请重新选择', 'error');
//                admin_error('错误', '当前后台账号已绑定其他人员【' . $exist->name_zh . '】，请重新选择');
                return back();
            }
        }
//        if (!empty($data['avatar'])) {
//            $cropper = new Crop('avatar');
//            $path    = $cropper->prepare($data['avatar']);
//            if (false === stripos($path, 'images')) {
//                $path = '';
//            }
//        }
        $data['avatar'] = $path;

        if (!empty($data['sequence_pid']) && is_array($data['sequence_pid'])) {
            $data['sequence_pid'] = array_filter($data['sequence_pid']);
        }

//        if (!empty($data['sequence_id']) && is_array($data['sequence_id'])) {
//            $data['sequence_id'] = array_filter($data['sequence_id']);
//        }

        $res = false;
        if ($id) {
            $res = $model->update($data);
        } elseif ($model->save($data)) {
            $res = $model->update($data);
        }

        if ($res) {
            admin_toastr('保存成功');
        } else {
            admin_toastr('保存失败', 'error');
        }

        return back();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $employeeId = !empty($this->data()) ? $this->data()['employee_id'] : 0;

        $this->hidden('employee_id', __('ID'));
        $this->number('order', __('优先级'))->default(1)->setWidth(4, 2)->rules('required|min:1')->required();
        $this->text('name_zh', __('姓名-中文'))->setWidth(2, 2)->rules('required|min:1|max:10')->maxlength(10)
            ->placeholder('输入姓名-中文，字符长度限制在10字符内')->required();
        $this->text('name_en', __('姓名-英文'))->setWidth(2, 2)->rules('required|min:1|max:30')->maxlength(30)
            ->placeholder('输入姓名-英文，字符长度限制在30字符内')->required();

        $teachers = UserModel::getTeacherList();
        !empty($teachers) && $teachers = array_column($teachers, 'name', 'id');
        $this->select('user_id', __('绑定后台登录账号'))->options($teachers)->setWidth(2, 2)->style('width', '160px')
            ->addElementClass('content-user-id');

        $sequences = SequenceModel::getSequenceList(['parent_id' => 0]);
        !empty($sequences) && $sequences = array_column($sequences, 'name_en', 'sequence_id');
//        $this->select('sequence_pid', __('岗位类别'))->options($sequences)->load('sequence_id', '/admin/sequence_select')->setWidth(2, 2)->required();
        $this->multipleSelect('sequence_pid', __('岗位分组'))->options($sequences)->setWidth(4, 2)
            ->placeholder('  请选择岗位分组，可多选')->required();

//        $sequencePid   = !empty($this->data()) ? $this->data()['sequence_pid'] : 0;
//        $sequenceLists = $sequencePid ? SequenceModel::getSequenceList(['parent_id' => $sequencePid]) : [];
//        !empty($sequenceLists) && $sequenceLists = array_column($sequenceLists, 'name_zh', 'sequence_id');
////        $this->select('sequence_id', __('职称'))->options($sequenceLists)->setWidth(2, 2)->required();
//        $this->multipleSelect('sequence_id', __('职称'))->options($sequenceLists)->setWidth(4, 2)->placeholder('  请选择职称，可多选')->required();

//        // 职位级别选项
//        $positionOptions = PositionModel::getPositionList();
//        !empty($positionOptions) && $positionOptions = array_column($positionOptions, 'name_zh', 'position_id');
//        $this->select('position_id', __('职位级别'))->options($positionOptions)->setWidth(2, 2);

//        $this->cropper('avatar', __('个人照片'))->cRatio(300, 400)->setWidth(6, 2)->help('照片固定宽高比例 3:4');
        $this->text('office_address_zh', __('Doctor of Philosophy'))->rules('nullable|min:0|max:120')->maxlength(120)
            ->placeholder('输入Ph.D.，字符长度限制在120字符内')->setWidth(4, 2);
        $this->text('research_direction_zh', __('Master of Science'))->rules('nullable|min:0|max:120')->maxlength(120)
            ->placeholder('输入M.Sc.，字符长度限制在120字符内')->setWidth(4, 2);
        $this->text('engineering', __('Master of Engineering'))->rules('nullable|min:0|max:120')->maxlength(120)
            ->placeholder('输入M.E.，字符长度限制在120字符内')->setWidth(4, 2);
        $this->text('personal_profile_zh', __('Bachelor of Engineering'))->rules('nullable|min:0|max:120')->maxlength(120)
            ->placeholder('输入B.E.，字符长度限制在120字符内')->setWidth(4, 2);

        // 学历身份
        $positionOptions = [
            '1' => 'Doctoral Student',
            '2' => 'Master Student',
            '3' => 'Undergraduate Student',
            '4' => 'Visiting Student'
        ];
        $this->select('position_id', __('学历身份'))->options($positionOptions)->setWidth(2, 2);
        $this->text('graduation_destination', __('Graduation destination'))->rules('nullable|min:0|max:120')->maxlength(120)
            ->placeholder('输入Graduation destination，字符长度限制在120字符内');
        $this->email('email', __('Email'))->rules('nullable|min:0|max:80')->maxlength(80)
            ->placeholder('输入Email，字符长度限制在80字符内')->setWidth(4, 2);
        $this->text('research_direction_en', __('Research Interests'))->rules('nullable|min:0|max:200')->maxlength(200)
            ->placeholder('输入Research Interests，字符长度限制在200字符内');
        $this->text('phone', __('办公电话'))->icon('fa-phone')->rules('nullable|min:0|max:32')->maxlength(32)
            ->placeholder('输入办公电话，字符长度限制在32字符内')->setWidth(4, 2);
        $this->url('personal_homepage', __('个人主页地址'))->rules('nullable|min:0|max:180')->maxlength(180)
            ->placeholder('输入个人主页地址，字符长度限制在180字符内')->setWidth(4, 2);
        $this->text('office_address_en', __('办公室地址'))->rules('nullable|min:0|max:180')->maxlength(180)
            ->placeholder('输入办公室地址，字符长度限制在180字符内')->setWidth(4, 2);
        $this->froala('personal_profile_en', __('个人简介'))->setContentId($employeeId)->setContentType(1);

        // 保存前回调
        $this->saving(function (Form $form) {
//            // 摘要从正文中截取摘要
//            $introduction_zh = !empty($form->content_zh) ? getIntroduction($form->content_zh, 300, '...') : '';
//            $form->model()->setAttribute('introduction_zh', $introduction_zh);

            if (is_array($form->user_id)) {
                $form->user_id = array_filter($form->user_id);
                $form->model()->setAttribute('user_id', $form->user_id[0]);
            }

//            if (is_array($form->position_id)) {
//                $form->position_id = array_filter($form->position_id);
//                $form->model()->setAttribute('position_id', $form->position_id[0]);
//            }

            if (is_array($form->sequence_pid)) {
                $form->model()->setAttribute('sequence_pid', array_filter($form->sequence_pid));
            }

//            if (is_array($form->sequence_id)) {
//                $form->model()->setAttribute('sequence_id', array_filter($form->sequence_id));
//            }
        });

        if ($this->isShow) {
            // 禁用重置
            $this->disableReset();
            // 禁用提交
            $this->disableSubmit();
        }

        // 添加样式
        \Encore\Admin\Admin::style(
            '.fileinput-remove {display:none;}'
        );

        // 文本提示样式设置
        \Encore\Admin\Admin::script(
            '$(".content-user-id").parent().parent().append("<div><span class=\"help-block\">'
            . '<i class=\"fa fa-info-circle\"><\/i> 没有账号的请去“系统管理》用户管理”处创建对应账号，照片也会同步使用<\/span><\/div>");'
        );
    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {
        $id = $this->getEmployeeId();

        $data = EmployeeModel::where('employee_id', '=', $id)->first();
        if (empty($data)) {
            return [];
        }

        $data = $data->toArray();

//        if (is_array($data['user_id'])) {
//            $data['user_id'] = array_filter($data['user_id']);
//            $data['user_id'] = $data['user_id'][0];
//        }
//
//        if (is_array($data['position_id'])) {
//            $data['position_id'] = array_filter($data['position_id']);
//            $data['position_id'] = $data['position_id'][0];
//        }

        if (is_array($data['sequence_pid'])) {
            $data['sequence_pid'] = array_filter($data['sequence_pid']);
        }

//        if (is_array($data['sequence_id'])) {
//            $data['sequence_id'] = array_filter($data['sequence_id']);
//        }

//        dd($data);
        return $data;
    }

    /**
     * 获取员工ID
     *
     * @return int
     */
    private function getEmployeeId()
    {
        $this->isShow = false === stripos(\Request::url(), 'edit') && false === stripos(\Request::url(), 'create');
        preg_match_all('/admin\/employee\/(\d+)/i', \Request::url(), $match);
        return !empty($match[1][0]) ? (int)$match[1][0] : 0;
    }
}
